package com.zzh.utils;

import com.zzh.entity.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author wenrouyue
 */
@Component
@Slf4j
public class MyUtils {
    @Resource
    private RedisCache redisCache;

    public String getMd5(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            return new BigInteger(1, md.digest()).toString(16);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public String creatCode() {
        int len = 6;
        StringBuilder code = new StringBuilder();
        Random r = new Random();
        for (int i = 0; i < len; i++) {
            int type = r.nextInt(3);
            switch (type) {
                case 0:
                case 1:
                    char ch = (char) (r.nextInt(26) + 97);
                    code.append(ch);
                    break;
                default:
                    code.append(r.nextInt(10));
                    break;
            }
        }
        return code.toString();
    }

    public String getLoginUserId() {
        String email = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!(authentication instanceof AnonymousAuthenticationToken)) {
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            email = loginUser.getUser().getId().toString();
        }
        LoginUser loginUser = redisCache.getCacheObject("login_" + email);
        log.info("从redis中获取用户信息:{}", loginUser);
        return loginUser.getUser().getId().toString();
    }

    public void delCacheByUserInfo(List<String> userIds) {
        try {
            redisCache.deleteObject(userIds);
            log.info("delCacheByUserInfo_开始删除用户:{},在缓存中的用户信息.", userIds);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("delCacheByUserInfo_抛出异常:{}", e.getMessage());
        }
    }

    public void delCacheByUserInfoByPrefix(List<String> prefix) {
        for (String s : prefix) {
            long l = redisCache.delObjs(s);
            log.info("delCacheByUserInfoByPrefix_删除前缀:{},{}条", prefix, l);
        }

    }

    /**
     * 返回从今天开始往前数多少天
     *
     * @param count 天数
     * @return 返回日期字符串
     */
    public List<String> computeDateByDays(int count, int days) {
        List<String> dateList = new ArrayList<>();
        Date date = new Date();
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
//        Date parse = f.parse(strDate);
        //起始 设置当前时间
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.setTime(date);
//        startCalendar.setTime(parse);
        //结束
        Calendar endCalendar = Calendar.getInstance();
        if (count == 1) {
            //第一次只需要当前时间减5天
            startCalendar.add(Calendar.DATE, -days);
            dateList.add(f.format(startCalendar.getTime()));
            //第一页查询明天和前五天
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(new Date());
            calendar.add(Calendar.DATE, +1);
            String tomorrow = f.format(calendar.getTime());
            dateList.add(tomorrow);
        } else {
            //设置从什么时间开始
            int day = count * days - days;
            Date startDate = computeDateBefore(day);
            startCalendar.setTime(startDate);
            //第一次只需要当前时间减5天
            startCalendar.add(Calendar.DATE, -days);
            dateList.add(f.format(startCalendar.getTime()));
            dateList.add(f.format(startDate));
        }
        return dateList;
    }

    /**
     * 计算当前日期多少天前是哪天
     *
     * @param day 天数
     * @return 日期
     */
    public Date computeDateBefore(int day) {
        Date date = new Date();
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.setTime(date);
        startCalendar.add(Calendar.DATE, -day);
        return startCalendar.getTime();
    }

    /**
     * 计算当前日期多少天后是哪天
     *
     * @param day 天数
     * @return 日期
     */
    public Date computeDateAfter(int day) {
        Date date = new Date();
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.setTime(date);
        startCalendar.add(Calendar.DATE, +day);
        return startCalendar.getTime();
    }

    /**
     * 拼接hash中的key
     *
     * @param userId 用户id
     * @param id     动态id
     * @return key
     */
    public String getUserIdAndDynamicId(String userId, String id) {
        String split = "::";
        return userId + split + id;
    }

    public boolean checkTime(Date time1, Date time2) {
        return time1.compareTo(time2) > 0;
    }

    public String getNewTime() {
        Date date = new Date();
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        return f.format(date);
    }

    public String getRegisterKey() {
        return getMd5(UUID.randomUUID().toString().replaceAll("-", "")).toUpperCase();
    }

    public Date getRoleTime(Integer num) {
        switch (num) {
            case 1:
                return computeDateAfter(1);
            case 7:
                return computeDateAfter(7);
            case 30:
                return computeDateAfter(30);
            case 120:
                return computeDateAfter(120);
            case 365:
                return computeDateAfter(365);
            default:
                String t = "2099-12-12";
                SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
                Date parse = null;
                try {
                    parse = f.parse(t);
                } catch (ParseException e) {
                    log.error(e.getMessage());
                }
                return parse;
        }

    }

    /**
     * 字符串转日期
     *
     * @param dateStr 日期字符串
     * @return 日期日期
     */
    public Date strToDate(String dateStr) {
        Date result;
        String format = "yyyy-MM-dd HH:mm:ss";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
        LocalDateTime dateTime = LocalDateTime.parse(dateStr, formatter);
        long milleSecond = dateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
        result = new Date(milleSecond);
        return result;
    }
    public Date strTimesToDate(String times) {
        Timestamp ts=new Timestamp(Long.parseLong(times));
        Date date=new Date(ts.getTime());
        return date;
    }

    public static void main(String[] args) {

        MyUtils myUtils = new MyUtils();
        Date date = myUtils.strToDate("2023-02-13 23:59:59");
        System.out.println(date);
        Date date1 = myUtils.computeDateBefore(7);
        System.out.println(date1);
//        String t = "2099-12-12";
//        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
//        System.out.println(f.format(myUtils.getRoleTime(7)));
//        System.out.println(f.format(myUtils.getRoleTime(30)));
//        System.out.println(f.format(myUtils.getRoleTime(120)));
//        System.out.println(f.format(myUtils.getRoleTime(365)));
//        System.out.println(f.format(myUtils.getRoleTime(1)));
    }
}
